package com.moore.service.Impl;

import com.moore.bean.Apartment;
import com.moore.bean.ApartmentForm;
import com.moore.dto.ResponseData;
import com.moore.mapper.ApartmentMapper;
import com.moore.service.ApartmentService;
import com.moore.service.EntitiesService;
import com.moore.utils.RoomNumberGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.moore.utils.Logger.toLog;

@Service
public class ApartmentServiceImpl implements ApartmentService {
    @Autowired
    private ApartmentMapper apartmentMapper;
    @Autowired
    private EntitiesService entitiesService;

    @Override
    public ResponseData confirmAddApartment(ApartmentForm apartmentForm) {
        List<String> roomNumbers = RoomNumberGenerator.generateRoomNumbers(apartmentForm);
        toLog("正在查找重复房间号");
        // 获取重复的房间号
        List<String> existingRoomNumbers = apartmentMapper.findExistingRoomNumbers(roomNumbers,apartmentForm.getAreaName(),apartmentForm.getCommunity());
        if (!existingRoomNumbers.isEmpty()) {
            // 格式化重复的房间号
            String formattedDuplicates = String.join("，", existingRoomNumbers);
            toLog("有"+existingRoomNumbers.size()+"个房间号重复");
            return new ResponseData(500, "房间号重复", formattedDuplicates, existingRoomNumbers.size());
        } else {
            toLog("房间号不重复，继续下一步操作");
            return new ResponseData(200,"房间号不重复",roomNumbers.toString(), roomNumbers.size());
        }
    }

    @Override
    public ResponseData addApartment(ApartmentForm apartmentForm) {
        toLog("正在批量生成房号");
        List<String> roomNumbers = RoomNumberGenerator.generateRoomNumbers(apartmentForm);
        toLog("正在添加套房信息");
        List<Apartment> apartments = new ArrayList<>();
        for (String roomNumber : roomNumbers) {
            apartments.add(new Apartment(
                    apartmentForm.getAreaName(),
                    apartmentForm.getCommunity(),
                    roomNumber,
                    apartmentForm.getArea(),
                    apartmentForm.getRooms(),
                    apartmentForm.getBathrooms(),
                    apartmentForm.getHalls(),
                    apartmentForm.getBalconies(),
                    apartmentForm.getRemark(),
                    apartmentForm.getRent(),
                    "未发布"
            ));
        }
        int result = apartmentMapper.addApartment(apartments);
        if (result > 0) {
            toLog("套房批量添加成功");
            return new ResponseData(200,"批量添加成功",result,result);
        } else {
            toLog("套房批量添加失败");
            return new ResponseData(500,"批量添加失败",null,0);
        }
    }

    @Override
    public ResponseData addAnApartment(Apartment apartment) {
        List<Apartment> apartments = apartmentMapper.getApartments(apartment);
        int result;
        if (!apartments.isEmpty()) result = apartmentMapper.addAnApartment(apartment);
        else result = apartmentMapper.updateAnApartment(apartment);
        if (result > 0) {
            toLog("套房添加/修改成功");
            return new ResponseData(200, "添加/修改成功", result, result);
        } else {
            toLog("套房添加/修改失败");
            return new ResponseData(500, "添加/修改失败", null, 0);
        }
    }

    @Override
    public ResponseData getBuildings(Apartment apartment) {
        List<String> buildings = apartmentMapper.getBuildings(apartment);
        toLog("获取楼栋成功");
        return new ResponseData(200,"获取楼栋成功",buildings,buildings.size());
    }

    @Override
    public ResponseData getApartments(Apartment apartment, HttpServletRequest request) {
        List<Apartment> apartments = apartmentMapper.getApartments(apartment);
        String serverUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        for (Apartment value : apartments) {
            if (!value.getImage().equals("https://via.placeholder.com/50")) {
                String relativePath = value.getImage();
                String fullPath = serverUrl + relativePath;
                value.setImage(fullPath);
            }
        }
        toLog("获取套房成功");
        return new ResponseData(200,"获取套房成功",apartments,apartmentMapper.getApartmentCount(apartment));

    }

    @Override
    public ResponseData updateApartmentStatus(String status, long id) {
        int result = apartmentMapper.updateApartmentStatus(status,id);
        String info;
        switch (status) {
            case "已发布": info = "发布"; break;
            case "已回收": info = "回收"; break;
            default:
                throw new IllegalStateException("Unexpected value: " + status);
        }
        if (result > 0) {
            toLog("套房" + info + "成功");
            return new ResponseData(200, "套房" + info + "成功", result, result);
        } else {
            toLog("套房" + info + "失败");
            return new ResponseData(500, "套房" + info + "失败", null, 0);
        }

    }

    @Override
    public ResponseData batchPublishApartments(List<Apartment> apartmentList) {
        toLog("正在判断套房状态");
        // 过滤掉 状态 为 "已发布"、"已租赁" 和 "已分配" 的 套房
        List<Apartment> filteredList = apartmentList.stream()
                .filter(apartment -> !("已发布".equals(apartment.getStatus()) ||
                        "已租赁".equals(apartment.getStatus()) ||
                        "已分配".equals(apartment.getStatus())))
                .collect(Collectors.toList());
        if (filteredList.isEmpty()){
            toLog("选择套房已发布");
            return new ResponseData(500,"套房已发布",null,0);
        }
        List<Long> ids = new ArrayList<>();
        for (Apartment apartment : filteredList) {
            ids.add(apartment.getId());
        }
        int result = apartmentMapper.batchPublishApartments(ids);
        StringBuilder apartments = new StringBuilder();
        for (Apartment apartment: filteredList){
            apartments.append(apartment.getRoomNumber());
        }
        if (result > 0) {
            toLog("套房批量发布成功");
            return new ResponseData(200, "批量发布成功",apartments.toString(), result);
        } else {
            toLog("套房批量发布失败");
            return new ResponseData(500, "批量发布失败", null, 0);
        }
    }

    @Override
    public ResponseData getApartmentsLayout(String areaName, String communityName) {
        List<String> apartmentsLayout = apartmentMapper.getApartmentsLayout(areaName,communityName);
        toLog("获取户型成功");
        return new ResponseData(200,"获取户型成功",apartmentsLayout,apartmentsLayout.size());
    }

    @Override
    public ResponseData getApartmentsArea(String areaName, String communityName) {
    List<String> apartmentsArea = apartmentMapper.getApartmentsArea(areaName,communityName);
        toLog("获取面积成功");
        return new ResponseData(200,"获取面积成功",apartmentsArea,apartmentsArea.size());
    }

    @Override
    public ResponseData getApartmentsRent(String areaName, String communityName) {
        List<String> apartmentsRent = apartmentMapper.getApartmentsRent(areaName,communityName);
        toLog("获取租金成功");
        return new ResponseData(200,"获取租金成功",apartmentsRent,apartmentsRent.size());
    }

    @Override
    public ResponseData deleteApartment(List<Apartment> apartments) {
         return entitiesService.deleteEntities(apartments,"room_number","已删除");
    }

    @Override
    public ResponseData reclaimApartment(List<Apartment> apartments) {
        return entitiesService.deleteEntities(apartments,"room_number","已回收");
    }

}
